﻿<%@ WebHandler Language="C#" Class="protectPhoneHandler" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using Chenxin.Lib.Utility;

public class protectPhoneHandler : AjaxHandlerBase
{
    public protectPhoneHandler()
    {
        htTypePermit.Add("protection", Constants.Permit_HouseProtection);
        htTypePermit.Add("unprotection", Constants.Permit_HouseUnProtection);
    }
    override public void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";

        string strOp = context.Request["op"];
        string strResponse = "";
        switch (strOp.ToLower())
        {
            case "protection":
                strResponse = protect(context);
                break;
            case "unprotection":
                strResponse = unProtect(context);
                break;
            default:
                break;
        }
        context.Response.Write(strResponse);
    }

    //*******************************************
    //功能概要       ：电话保护
    //参数説明       ：houseid 房源主键 houseCode 房源编号 shouseAddress房源地址 traceContext 跟单内容
    //返回值説明     ：void
    //功能詳細       ：根据房源编号获得房源信息
    //作成者         ：chen.yugong 
    //作成日         ：2010-03-01
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string protect(HttpContext context)
    {
       try
        {
            //转换成实体
            Chenxin.Lib.House.Entity.House_BaseInfo model = (Chenxin.Lib.House.Entity.House_BaseInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_BaseInfo));
            if (model.HouseId == null)
                return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "房源标识丢失，请联系管理员！");

            Chenxin.Lib.House.Entity.House_BaseInfo house_BaseInfo = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(model.HouseId);
            if (house_BaseInfo == null)
                return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "房源信息丢失，请联系管理员！");
         
            /* 检查保护数量 
             * 从表查出保护数量
             * 从House_BaseInfo中count出已保护房源  条件 已保护且不是自动保护
             */
           Chenxin.Lib.House.Entity.House_BusinessSetting bs = Chenxin.Lib.House.DAL.House_BusinessSetting.GetModel(CurrentUserInfo.DepartId);

           string strSql = string.Format("select count(*) as countNum from House_BaseInfo where OprDepartId = '{0}' AND IsAutoProPhone = '{1}' and IsProtectPhone = '{2}'", CurrentUserInfo.DepartId, false, true);
            DataSet dataset = Chenxin.Lib.House.DAL.House_BaseInfo.GetListBySql(strSql);
            if(bs!=null) {
                int count = (int)dataset.Tables[0].Rows[0][0];
                if (count >= bs.ProtectedNum)
                {
                    return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "已超出最大保护数量，请联系管理员！");
                }
            }
            house_BaseInfo.IsProtectPhone = true;
            house_BaseInfo.DisplayPhone = model.DisplayPhone;
            house_BaseInfo.UpdateTime = DateTime.Now;
            house_BaseInfo.ServiceTime = DateTime.Now;
            Chenxin.Lib.House.DAL.House_BaseInfo.Update(house_BaseInfo);
            //清除缓存
            string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_HOUSEINFO, model.HouseId);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            cs.Delete(strCachKey);
            
            //添加跟单记录
            Chenxin.Lib.House.Entity.House_TraceInfo house_TraceInfo = new Chenxin.Lib.House.Entity.House_TraceInfo();
            //跟单方式
            house_TraceInfo.TraceType = 0;
            //跟单内容	 
            house_TraceInfo.TraceContext = CurrentUserInfo.UserName+ "设置了电话保护。";
            //房源Id	 
            house_TraceInfo.HouseId = house_BaseInfo.HouseId;
            //房源编号	
            house_TraceInfo.HouseCode = house_BaseInfo.HouseCode;
            //房源地址	 
            house_TraceInfo.HouseAddress = house_BaseInfo.Community + house_BaseInfo.BuildingName + house_BaseInfo.Room;
            house_TraceInfo.status = 0;

            house_TraceInfo.OprDepart = house_BaseInfo.OprDepart;
            house_TraceInfo.OprDepartId = house_BaseInfo.OprDepartId;
            house_TraceInfo.OprPerson = house_BaseInfo.OprPerson;
            house_TraceInfo.OprPersonId = house_BaseInfo.OprPersonId;
            AddTrace(house_TraceInfo);
           
            //添加用户操作日志 2010-5-11 王玮 Add
            AddLog("" + CurrentUserInfo.UserName + "添加了一个电话保护:[" + house_BaseInfo.Community + house_BaseInfo.BuildingName + house_BaseInfo.Room + "]房源已添加电话保护。",
                    OperationType.OperationTypeComboList()["OprType_PhoneProtectionAdd"].ToString());

            return string.Format("{{success:'1',msg:'{0}',data:{{}}}}", "保护成功！");
        }
       catch (Exception ex)
       {
           return string.Format("{{success:'0',msg:'意外错误：{0}',data:{{}}}}", ex.Message);
       }
       
    }


    //*******************************************
    //功能概要       ：电话保护取消
    //参数説明       ：houseid 房源主键
    //返回值説明     ：void
    //功能詳細       ：电话保护取消
    //作成者         ：chen.yugong 
    //作成日         ：2010-03-01
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string  unProtect(HttpContext context)
    {
        try
        {
            string HouseId = context.Request["modelid"];
            if (string.IsNullOrEmpty(HouseId))
            {
                return string.Format("{{success:'0',msg:'{0}：{0}',data:{{}}}}", "房源标识丢失，请联系管理员！");
            }
            
            Chenxin.Lib.House.Entity.House_BaseInfo house_BaseInfo = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(new Guid(HouseId));
            if (house_BaseInfo == null)
                return string.Format("{{success:'0',msg:'{0}：{0}',data:{{}}}}", "房源信息丢失，请联系管理员！");
            
            //更新保护电话
            house_BaseInfo.IsProtectPhone = false;
            house_BaseInfo.IsAutoProPhone = false;
            house_BaseInfo.UpdateTime = DateTime.Now;
            house_BaseInfo.ServiceTime = DateTime.Now;
            house_BaseInfo.DisplayPhone = "";
            Chenxin.Lib.House.DAL.House_BaseInfo.Update(house_BaseInfo);

            //清除缓存
            string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_HOUSEINFO, house_BaseInfo.HouseId);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            cs.Delete(strCachKey);
            
            //添加跟单记录
            Chenxin.Lib.House.Entity.House_TraceInfo house_TraceInfo = new Chenxin.Lib.House.Entity.House_TraceInfo();
            //跟单方式	
            house_TraceInfo.TraceType = 0;
            //跟单内容	 
            house_TraceInfo.TraceContext = CurrentUserInfo.UserName + "取消了电话保护。";
            //房源Id	 
            house_TraceInfo.HouseId = house_BaseInfo.HouseId;
            //房源编号	
            house_TraceInfo.HouseCode = house_BaseInfo.HouseCode;
            //房源地址	 
            house_TraceInfo.HouseAddress = house_BaseInfo.Community + house_BaseInfo.BuildingName + house_BaseInfo.Room;
            house_TraceInfo.status = 0;
            house_TraceInfo.OprDepart = house_BaseInfo.OprDepart;
            house_TraceInfo.OprDepartId = house_BaseInfo.OprDepartId;
            house_TraceInfo.OprPerson = house_BaseInfo.OprPerson;
            house_TraceInfo.OprPersonId = house_BaseInfo.OprPersonId;
            AddTrace(house_TraceInfo);
            
            //添加用户操作日志 2010-5-11 王玮 Add
            AddLog("" + CurrentUserInfo.UserName + "取消了一个电话保护:[" + house_BaseInfo.Community + house_BaseInfo.BuildingName + house_BaseInfo.Room + "]房源已取消电话保护。",
                    OperationType.OperationTypeComboList()["OprType_PhoneProtectionCel"].ToString());
            
            return string.Format("{{success:'1',msg:'{0}',data:{{}}}}", "取消保护成功！");
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:{{}}}}", ex.Message);
        }
    }
    public bool IsReusable {
        get {
            return false;
        }
    }
    //*******************************************
    //功能概要       ：响应字符串
    //参数説明       ：strMsg 消息 
    //返回值説明     ：void
    //功能詳細       ：权限检查
    //作成者         ：chen.yugong 
    //作成日         ：2010-05-20
    //修改者         ：
    //修改日         ：
    //*******************************************
    public override bool CustomerCheckPermint(HttpContext context, out string strMsg)
    {
        if (context.Request["op"] != null)
        {
            string op = context.Request["op"].ToLower();
            //如果是保护和取消保护
            if ((op.Equals("checkpermit") && "protection".Equals(context.Request["code"].ToLower())) || op.Equals("unprotection"))
            {
                Chenxin.Lib.House.Entity.House_BaseInfo model = null;
                //保护
                if (op.Equals("checkpermit") && "protection".Equals(context.Request["code"].ToLower()))
                {
                     try{
                        model = (Chenxin.Lib.House.Entity.House_BaseInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_BaseInfo));
                     }
                     catch (Exception e)
                     {
                        strMsg = "{success:0,msg:'"+e.Message+"',data:''}";
                        return false;
                     }
                     if (CurrentUserInfo.ContainsPermit(Constants.Permit_TelphoneHouse_All))
                     {
                        strMsg = "{success:1,msg:'',data:{permit:true}}";
                        return true;
                     }
                     else if (CurrentUserInfo.ContainsPermit(Constants.Permit_TelphoneHouse_City))
                     {
                        if (CurrentUserInfo.CityId.Equals(model.CityId))
                        {
                            strMsg = "{success:1,msg:'',data:{permit:true}}";
                            return true;
                        }
                        else
                        {
                            strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                            return false;
                        }
                     }
                     else if (CurrentUserInfo.ContainsPermit(Constants.Permit_TelphoneHouse_Company))
                     {
                        if (CurrentUserInfo.CompanyId.Equals(model.CompanyId))
                        {
                            strMsg = "{success:1,msg:'',data:{permit:true}}";
                            return true;
                        }
                        else
                        {
                            strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                            return false;
                        }
                    }
                    else if (CurrentUserInfo.ContainsPermit(Constants.Permit_TelphoneHouse_Department))
                    {
                        if (checkDepartPermit("protection", model.OprDepartId,  CurrentUserInfo.UserId))
                        {
                             strMsg = "{success:1,msg:'',data:{permit:true}}";
                             return true;
                        }
                        else
                        {
                            strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                            return false;
                        }
                    }
                    else
                    {
                         strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                         return false;
                    }

                 }
                if (op.Equals("unprotection"))
                {
                    string id = context.Request["modelid"];
                    if (string.IsNullOrEmpty(id))
                    {
                        strMsg = "{success:0,msg:'房源获取数据失败！',data:''}";
                        return false;
                    }
                    model = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(new Guid(id));
                    if (model == null)
                    {
                        strMsg = "{success:0,msg:'房源获取数据失败！',data:''}";
                        return false;
                    }
                    if (CurrentUserInfo.ContainsPermit(Constants.Permit_UnTelphoneHouse_All))
                    {
                        strMsg = "{success:1,msg:'',data:{permit:true}}";
                        return true;
                    }

                    else if (CurrentUserInfo.ContainsPermit(Constants.Permit_UnTelphoneHouse_City))
                    {
                        if (CurrentUserInfo.CityId.Equals(model.CityId))
                        {
                            strMsg = "{success:1,msg:'',data:{permit:true}}";
                            return true;
                        }
                        else
                        {
                            strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                            return false;
                        }
                    }
                    else if (CurrentUserInfo.ContainsPermit(Constants.Permit_UnTelphoneHouse_Company))
                    {
                        if (CurrentUserInfo.CompanyId.Equals(model.CompanyId))
                        {
                            strMsg = "{success:1,msg:'',data:{permit:true}}";
                            return true;
                        }
                        else
                        {
                            strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                            return false;
                        }
                    }
                    else if (CurrentUserInfo.ContainsPermit(Constants.Permit_UnTelphoneHouse_Department))
                    {
                        if (checkDepartPermit("protection", model.OprDepartId, CurrentUserInfo.UserId))
                        {
                            strMsg = "{success:1,msg:'',data:{permit:true}}";
                            return true;
                        }
                        else
                        {
                            strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                            return false;
                        }
                    }
                    else
                    {
                        strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                        return false;
                    }   
               }
            }
        }
        strMsg = "{success:1,msg:'',data:{permit:true}}";
        return true;
    }
    
    //*******************************************
    //功能概要       ：部门内有无保护权限
    //参数説明       ：context 上下文
    //返回值説明     ：bool
    //功能詳細       ：部门内有无封盘解盘权限
    //作成者         ：chen.yugong 
    //作成日         ：2010-05-19
    //修改者         ：
    //修改日         ：
    //*******************************************
    public bool checkDepartPermit(string op, Guid departId, Guid userId)
    {
        //检查有无权限
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.AppendFormat(" (Departid = '{0}' AND  Userid= '{1}') ", departId, userId);
        System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation> list = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.GetListArray(sb.ToString());
        if (list.Count > 0)
        {
            Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation struct_UserDepartRelation = list[0];
            if ("protection".Equals(op) || "unprotection".Equals(op))
            {
                return struct_UserDepartRelation.CanProtect;
            }
        }
        return false;
    }

}